package com.lvmama.controller.rhino.flow;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.client.rhino.FlowConversionClient;
import com.lvmama.client.rhino.MenuClient;
import com.lvmama.client.rhino.SearchStatisticsClient;
import com.lvmama.common.enums.CommonParentType;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.DateUtil;
import com.lvmama.common.utils.JSONConversionUtil;
import com.lvmama.config.ElasticsearchConfig;
import com.lvmama.pojo.dto.rhino.flow.FlowAndRateData;
import com.lvmama.pojo.dto.rhino.flow.FlowConversionDTO;
import com.lvmama.pojo.dto.rhino.flow.FlowFunnelData;
import com.lvmama.pojo.dto.rhino.flow.FlowStatisticsFunnel;
import com.lvmama.pojo.dto.rhino.page.FlowStatisticsVo;
import com.lvmama.pojo.entity.rhino.page.FlowData;
import com.lvmama.pojo.entity.rhino.system.Menu;
import com.lvmama.pojo.entity.rhino.system.User;
import com.lvmama.pojo.entity.rhino.topic.StatisticCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @ClassName : FlowConversionController
 * @Description : 流量转化
 * @Author :dongq
 * @Date : 2018/9/3 11:35
 * @Version V1.0
 **/
@Slf4j
@Controller
@RequestMapping("traffic")
public class FlowConversionController {
    @Autowired
    private  FlowConversionClient flowConversionClient;
    @Autowired
    private SearchStatisticsClient searchStatisticsClient;
    @Autowired
    private MenuClient menuClient;
    @Autowired
    private ElasticsearchConfig template;

    @RequestMapping(value = "/transform",method = RequestMethod.GET)
    public String transform(ModelMap model) {
        // 通过枚举获得品类的信息
        CommonParentType[] getVSTProduct = CommonParentType.geAllCategory();
        List<CommonParentType> vSTProductlist = Arrays.asList(getVSTProduct);
        model.addAttribute("vSTProductlist", vSTProductlist);
        // 从数据库查询SEM着陆页或SEO着陆页名称
        List<StatisticCode> semSeoCodeList = flowConversionClient.getLikeCodeObj("3");
        for (int i = 0; i < semSeoCodeList.size(); i++) {
            String code = semSeoCodeList.get(i).getCode();
            if (code.equals("3")) {
                semSeoCodeList.get(i).setName("全部");
                semSeoCodeList.get(i).setCode("");
            } else if (code.equals("3zhTi") || code.equals("3PinD")) {
                semSeoCodeList.remove(i);
            }
        }
        model.addAttribute("semSeoCodeList", semSeoCodeList);
        // 从数据库查询SEO流量来源
        List<StatisticCode> seoCodeList = flowConversionClient.getLikeCodeObj("123");
        for (StatisticCode statisticCode : seoCodeList) {
            if (statisticCode.getCode().equals("123")) {
                statisticCode.setName("全部");
                statisticCode.setCode("");
            }
        }
        model.addAttribute("seoCodeList", seoCodeList);
        // 从数据库查询社交分享
        List<StatisticCode> socialCodeList = flowConversionClient.getLikeCodeObj("121");
        for (StatisticCode statisticCode : socialCodeList) {
            if (statisticCode.getCode().equals("121")) {
                statisticCode.setName("全部");
                statisticCode.setCode("");
            }
        }
        model.addAttribute("socialCodeList", socialCodeList);
        return "/flow/transformList";
    }

    /**
     * 流量转化-不同详情
     *
     * @param flowDTO
     * @return
     */
    @RequestMapping(value = "/queryfunnel",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryFunnel(FlowConversionDTO flowDTO){
        log.info("FlowConversionController queryFunnel start");
        List<String> StatisticCodeList = new ArrayList<String>();
        if(Strings.isBlank(flowDTO.getPlatformCode())){
            StatisticCodeList = searchStatisticsClient.getDeviceCodeByLikeName(flowDTO.getPlatform());
        }
        flowDTO.setBeginDate(DateUtil.formatString(flowDTO.getBeginDate(),"MM/dd/yyyy","yyyy/MM/dd"));
        flowDTO.setEndDate(DateUtil.formatString(flowDTO.getEndDate(),"MM/dd/yyyy","yyyy/MM/dd"));

        String sqlFlag = "1";
        String parentId = null;
        String platformAll = null;
        String channelCode = flowDTO.getChannelCode();
        if ("app".equalsIgnoreCase(flowDTO.getTabId())) {
            sqlFlag = "2";
            channelCode = "116yq5";
            if (flowDTO.getPlatform() == null || flowDTO.getPlatform() == "") {
                platformAll = "2g53";
            }
        } else if ("Wap".equalsIgnoreCase(flowDTO.getTabId())) {
            sqlFlag = "3";
            channelCode = "116yq5";
            if (flowDTO.getPlatform() == null || flowDTO.getPlatform() == "") {//platform为空，查询全部PC，wap的流量  modified by shibing 2017-08-25
                StatisticCodeList = flowConversionClient.getDeviceCodeByLikeNamePcAndWap(flowDTO.getPlatform());
            }
        } else if ("SEM".equalsIgnoreCase(flowDTO.getTabId())) {
            channelCode = "12h";
        } else if ("SEO".equalsIgnoreCase(flowDTO.getTabId())) {
            if (flowDTO.getChannelCode() == null || flowDTO.getChannelCode() == "") {
                parentId = "7";
            }
        } else if ("Society".equalsIgnoreCase(flowDTO.getTabId())) {
            if (flowDTO.getChannelCode() == null || flowDTO.getChannelCode() == "") {
                parentId = "6";
            }
        }
        flowDTO.setChannelCode(channelCode);
        flowDTO.setParentId(parentId);
        flowDTO.setPlatformAll(platformAll);
        flowDTO.setStatisticCodeList(StatisticCodeList);

        List<FlowStatisticsVo> list = null;
        if ("2".equals(sqlFlag)) {
            list = flowConversionClient.getFlowbyApp(flowDTO).getData();
        } else if ("3".equals(sqlFlag)) {//PC/M站直接访问流量统计 add by shibing 2017-08-25
            list = flowConversionClient.getFlowbyChannelWap(flowDTO).getData();
        } else {
            list = flowConversionClient.getFlowbyChannel(flowDTO).getData();
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("list", list);
        log.info("FlowConversionController queryFunnel end");
        return resultMap;
    }

    /**
     * 筛选出所有漏斗
     */
    @RequestMapping(value = "getAllFunnelList",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getAllFunnelList(FlowStatisticsFunnel funnel, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        PageInfo<FlowStatisticsFunnel> page = flowConversionClient.getAllFunnel(funnel).getData();
        result.put("pageData", page);
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        List<Menu> menuList = menuClient.getAllMenuListByUser(currentUser).getData();
        if (null != menuList && menuList.size() > 0) {
            for (Menu menu : menuList) {
                if (StringUtils.isNotEmpty(menu.getPermission())) {
                    if (menu.getPermission().contains("sys:funnel:new")) {
                        result.put("newFunnelPermission", true);
                    }
                    if (menu.getPermission().contains("sys:funnel:delete")) {
                        result.put("deleteFunnelPermission", true);
                    }
                    if (menu.getPermission().contains("sys:funnel:edit")) {
                        result.put("editFunnelPermission", true);
                    }

                }
            }
        }
        return result;
    }

    /**
     * 筛选出所有漏斗
     */
    @RequestMapping("getFunnelChart")
    @ResponseBody
    public Map<String, Object> getFunnelChart(FlowConversionDTO flowDTO) throws Exception {
        log.info("FlowConcersionController getFunnelChart start");
        Map<String, Object> result = new HashMap<>();

        String platForm = flowDTO.getPlatform();
        List<String> statisticCodeList = new ArrayList<String>();
        if (StringUtils.isEmpty(platForm)) {
            statisticCodeList.add(flowDTO.getVersion());
        } else if (platForm.equals("app")) {
            statisticCodeList = searchStatisticsClient.getDeviceCodeApp();
        } else if (platForm.equals("ios")) {
            statisticCodeList = searchStatisticsClient.getDeviceCodeByLikeName("ios");
        } else if (platForm.equals("android")) {
            statisticCodeList = searchStatisticsClient.getDeviceCodeByLikeName("android");
        } else if (platForm.equals("wap")) {
            statisticCodeList = searchStatisticsClient
                    .getDeviceCodeByLikeName("wap");
        } else if (platForm.equals("all")) {
            statisticCodeList = flowConversionClient.getLikeCodes("2");
        }

        String beginDate = DateUtil.formatString(flowDTO.getBeginDate(),"MM/dd/yyyy","yyyy/MM/dd").replace("/","");
        String endDate = DateUtil.formatString(flowDTO.getEndDate(),"MM/dd/yyyy","yyyy/MM/dd").replace("/","");

        FlowFunnelData funnelData = new FlowFunnelData();
        funnelData.setBeginDate(beginDate);
        funnelData.setEndDate(endDate);
        funnelData.setPlatformCodeList(statisticCodeList);

        FlowStatisticsFunnel funnel = new FlowStatisticsFunnel();
        funnel.setFunnelId(Integer.valueOf(flowDTO.getFunnelId()));

        List<FlowStatisticsFunnel> funnelDetailList = flowConversionClient.getFunnelDetail(funnel).getData();
        String reg = "";
        if (funnelDetailList != null && funnelDetailList.size() > 0) {
            int i = 0;
            for (FlowStatisticsFunnel f : funnelDetailList) {
                if (f.getFunnelType().equals("0")) {
                    f.setCategoryName(CommonParentType.getCategoryShowName(String.valueOf(f.getParamId())));
                }
                if (i > 0) {
                    reg += ".*";
                }
                reg += f.getPageCode();
                if (f.getFunnelType().equals("0")) {
                    if (f.getPageCode().startsWith("3PinD")) {
                        reg += ",-?[0-9]*,-?[0-9]*";
                    } else {
                        reg += "," + f.getParamId() + ",-?[0-9]*";
                    }
                } else {
                    if (f.getPageCode().startsWith("3PinD")) {
                        reg += ",-?[0-9]*,-?[0-9]*";
                    } else {
                        reg += ",-?[0-9]*," + f.getParamId();
                    }
                }
                long value = getPathNum(flowDTO.getVisitType(), reg, funnelData);
                log.info("---------第" + i + "步骤值:" + value);
                f.setAmount(value);
                i++;
            }
            result.put("funnelName", funnelDetailList.get(0).getName());
        }
        result.put("funnelDetailList", funnelDetailList);
        log.info("FlowConcersionController getFunnelChart end");
        return result;
    }

    /**
     * 流量转化（流量来源及占比）
     * @param flowDTO
     * @return
     */
    @RequestMapping("queryFlowStatisticsData")
    @ResponseBody
    public Map<String, Object> queryFlowStatisticsData(FlowConversionDTO flowDTO){
        log.info("FlowConversionController queryFlowStatisticsData start");
        List<String> StatisticCodeList = searchStatisticsClient.getDeviceCodeByLikeName("");

        flowDTO.setBeginDate(DateUtil.formatString(flowDTO.getBeginDate(),"MM/dd/yyyy","yyyy/MM/dd"));
        flowDTO.setEndDate(DateUtil.formatString(flowDTO.getEndDate(),"MM/dd/yyyy","yyyy/MM/dd"));
        flowDTO.setStatisticCodeList(StatisticCodeList);
        FlowData flowData = flowConversionClient.getFlowStatisticsData(flowDTO).getData();

        Long totalAmount = 0l;
        List<FlowAndRateData> list = null;
        if (flowData != null) {
            Long appFlowAmount = flowData.getAppFlowAmount() != null ? flowData.getAppFlowAmount() : 0l;
            Long wapFlowAmount = flowData.getWapFlowAmount() != null ? flowData.getWapFlowAmount() : 0l;
            Long semFlowAmount = flowData.getSemFlowAmount() != null ? flowData.getSemFlowAmount() : 0l;
            Long seoFlowAmount = flowData.getSeoFlowAmount() != null ? flowData.getSeoFlowAmount() : 0l;
            Long societyFlowAmount = flowData.getSocietyFlowAmount() != null ? flowData.getSocietyFlowAmount() : 0l;
            flowData.setAppFlowAmount(appFlowAmount);
            flowData.setWapFlowAmount(wapFlowAmount);
            flowData.setSemFlowAmount(semFlowAmount);
            flowData.setSeoFlowAmount(seoFlowAmount);
            flowData.setSocietyFlowAmount(societyFlowAmount);
            totalAmount = appFlowAmount + wapFlowAmount + semFlowAmount + seoFlowAmount + societyFlowAmount;
            list = flowDataToFlowAndRateList(flowData,   totalAmount);
        }

        int defaultLength = 5;
        Long[] seriesDataf = new Long[defaultLength];
        String[] xAxisDataf = new String[defaultLength];
        if (list != null && !list.isEmpty()) {
            int i = 0;
            for (FlowAndRateData flowStatistics : list) {
                if (i < defaultLength) {
                    seriesDataf[i] = flowStatistics.getFlowData();
                    xAxisDataf[i] = i + 1 + "";
                }
                i++;
            }
        }

        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap.put("list", list);
        resultMap.put("amountF", totalAmount);
        resultMap.put("defaultLength", defaultLength);
        resultMap.put("seriesDataf", seriesDataf);
        resultMap.put("xAxisDataf", xAxisDataf);
        log.info("FlowConversionController queryFlowStatisticsData end");
        return resultMap;
    }

    /**
     * 根据平台获得版本类型
     *
     * @param platForm
     * @return
     */
    @RequestMapping("appVersion")
    @ResponseBody
    public Map<String, Object> queryAppVersion(String platForm) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        // 根据code码获得其子级的code码信息
        List<StatisticCode> codeList = flowConversionClient.getLikeCodeObj("2");
        if (platForm != "") {
            for (StatisticCode statisticCode : codeList) {
                if (statisticCode.getName().startsWith(platForm)) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    String appVersionName = statisticCode.getName().replace(platForm, "");
                    map.put("name", appVersionName);
                    map.put("value", statisticCode.getCode());
                    list.add(map);
                }
            }
        }
        result.put("msg", list);
        return result;
    }

    /**
     * 筛选出漏斗详情
     */
    @RequestMapping("getFunnelDetailList")
    @ResponseBody
    public Map<String, Object> getFunnelDetailList(FlowStatisticsFunnel funnel) {
        Map<String, Object> result = new HashMap<>();
        flowConversionClient.updateFunnel(funnel);
        List<FlowStatisticsFunnel> funnelDetailList = flowConversionClient.getFunnelDetail(funnel).getData();
        if (funnelDetailList != null && funnelDetailList.size() > 0) {
            for (FlowStatisticsFunnel f : funnelDetailList) {
                if (f.getFunnelType().equals("0")) {
                    f.setFunnelType("品类");
                    f.setCategoryName(CommonParentType.getCategoryShowName(String.valueOf(f.getParamId())));
                } else {
                    f.setFunnelType("产品");
                }
            }
        }
        result.put("funnelDetailList", funnelDetailList);
        return result;
    }

    /**
     * 筛选出指定漏斗
     */
    @RequestMapping("selectFunnel")
    @ResponseBody
    public Map<String, Object> selectFunnel(FlowStatisticsFunnel funnel) {
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isNotEmpty(funnel.getFunnelType())) {
            if (funnel.getFunnelType().equals("品类")) {
                funnel.setFunnelType("0");
            } else {
                funnel.setFunnelType("1");
            }

        }
        FlowStatisticsFunnel data = flowConversionClient.getFunnel(funnel).getData();
        result.put("funnel", data);
        return result;
    }
    /**
     * 获得所有品类
     */
    @RequestMapping("getAllCategory")
    @ResponseBody
    public Map<String, Object> getAllCategoryList() {
        Map<String, Object> result = new HashMap<>();
        CommonParentType[] categorys = CommonParentType.geAllCategory();
        Map<String, String> categoryMap = new HashMap<String, String>();
        for (CommonParentType category : categorys) {
            categoryMap.put(category.getValue(), category.getShowName());
        }
        result.put("categoryMap", categoryMap);
        return result;
    }
    /**
     * 保存自定义漏斗
     */
    @RequestMapping("savaFunnel")
    @ResponseBody
    public Result savaFunnel(@RequestParam("jsondata") String jsondata,HttpServletRequest request) {
        JSONObject jsonObject = JSONConversionUtil.stringToObj(jsondata,JSONObject.class);
        FlowStatisticsFunnel funnel = new FlowStatisticsFunnel();
        funnel.setName(jsonObject.getString("name"));
        if (jsonObject.getString("funnelType").equals("品类")) {
            funnel.setFunnelType("0");
        } else {
            funnel.setFunnelType("1");
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        funnel.setOperator(user.getName());
        funnel.setCreateTime(new Date());
        funnel.setEditTime(new Date());
        int funnelId = 0;
        if (StringUtils.isNotEmpty(jsonObject.getString("funnelId"))) {
            funnelId = Integer.valueOf(jsonObject.getString("funnelId"));
            funnel.setFunnelId(funnelId);
            flowConversionClient.updateFunnel(funnel);
            List<String> list = new ArrayList<>();
            list.add(String.valueOf(funnelId));
            funnel.setFunnelIds(list);
            flowConversionClient.deleteFunnelDetail(funnel);
        } else {
            flowConversionClient.insertFunnel(funnel);
            FlowStatisticsFunnel flowStatisticsFunnel = flowConversionClient.getFunnel(funnel).getData();
            funnelId = flowStatisticsFunnel.getFunnelId();
        }
        JSONArray jarry = jsonObject.getJSONArray("list");
        for (int i = 0; i < jarry.size(); i++) {
            JSONObject obj = jarry.getJSONObject(i);
            String stepIndex = obj.getString("stepIndex");
            String pageName = obj.getString("pageName");
            String paramId = obj.getString("categoryName");
            String pageCode = obj.getString("pageCode");
            FlowStatisticsFunnel f = new FlowStatisticsFunnel();
            f.setFunnelId(funnelId);
            f.setStepIndex(Integer.valueOf(stepIndex));
            f.setPageName(pageName);
            if (jsonObject.getString("funnelType").equals("品类")) {
                f.setParamId(Integer.valueOf(CommonParentType
                        .getCategoryValueByShowName(paramId)));
            } else {
                f.setParamId(Integer.valueOf(paramId));
            }
            f.setPageCode(pageCode);
            flowConversionClient.insertFunnelDetail(f);
        }
        return Result.success(true);
    }

    /**
     * 删除漏斗
     */
    @RequestMapping("deleteFunnel")
    @ResponseBody
    public Result deleteFunnel(@RequestParam("funnelIds") String funnelIds) {
        log.info("FlowConversionController deleteFunnel start");
        String[] funnelIdArr = funnelIds.split(",");
        FlowStatisticsFunnel funnel = new FlowStatisticsFunnel();
        funnel.setFunnelIds(Arrays.asList(funnelIdArr));
        try{
            flowConversionClient.deleteFunnel(funnel);
            flowConversionClient.deleteFunnelDetail(funnel);
        }catch (Exception e){
            log.error("FlowConversionController deleteFunnel error:{}",e.getMessage());
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("FlowConversionController deleteFunnel start");
        return Result.success(true);
    }

    /**
     * 获得频道code
     */
    @RequestMapping("getPindaoCode")
    @ResponseBody
    public Map<String, Object> getPindaoCode(String name) {
        Map<String, Object> result = new HashMap<>();
        StatisticCode code = new StatisticCode();
        code.setParentId(280);
        code.setName(name);
        StatisticCode statisticCode = flowConversionClient.selectStatisticCode(code);
        result.put("statisticCode", statisticCode);
        return result;
    }

    /**
     * 获得频道子集
     */
    @RequestMapping("getPindaoParent")
    @ResponseBody
    public Map<String, Object> getPindaoParent() {
        Map<String, Object> result = new HashMap<>();
        List<StatisticCode> statisticCodeList = flowConversionClient.getLikeCodeObjNotParent("3PinD");
        result.put("statisticCodeList", statisticCodeList);
        return result;
    }


    /**
     * @param @param flowData 设定文件
     * @return void 返回类型
     * @throws
     * @Title: flowDataToFlowAndRateList
     * @Description: (将查处的数据转换为list)
     */
    private List<FlowAndRateData> flowDataToFlowAndRateList(FlowData flowData,Long totalAmount) {
        List<FlowAndRateData> list = new ArrayList<FlowAndRateData>();
        DecimalFormat df = new DecimalFormat("#.00");

        FlowAndRateData data = new FlowAndRateData();
        data.setFlowSource("APP直接访问");
        if (flowData != null) {
            data.setFlowData(flowData.getAppFlowAmount());
        }
        list.add(data);

        FlowAndRateData data1 = new FlowAndRateData();
        data1.setFlowSource("M站直接访问");
        if (flowData != null) {
            data1.setFlowData(flowData.getWapFlowAmount());
        }
        list.add(data1);

        FlowAndRateData data2 = new FlowAndRateData();
        data2.setFlowSource("SEM");
        if (flowData != null) {
            data2.setFlowData(flowData.getSemFlowAmount());
        }
        list.add(data2);

        FlowAndRateData data3 = new FlowAndRateData();
        data3.setFlowSource("SEO");
        if (flowData != null) {
            data3.setFlowData(flowData.getSeoFlowAmount());
        }
        list.add(data3);

        FlowAndRateData data4 = new FlowAndRateData();
        data4.setFlowSource("社交分享");
        if (flowData != null) {
            data4.setFlowData(flowData.getSocietyFlowAmount());
        }
        list.add(data4);
        // 计算各来源占比
        if (list != null && !list.isEmpty()) {
            for (FlowAndRateData flowStatistics : list) {
                if (totalAmount != 0 && flowStatistics.getFlowData() > 0) {
                    String rat = df.format(((double) flowStatistics.getFlowData() / totalAmount) * 100);
                    flowStatistics.setFlowRate(rat);
                } else {
                    flowStatistics.setFlowRate("0.00");
                }
            }
        }

        // 各来源按照流量进行降序排列
        Collections.sort(list, new Comparator<FlowAndRateData>() {
            /*
             * int compare(FlowAndRateData o1, FlowAndRateData o2) 返回一个基本类型的整型，
             * 返回负数表示：o1 小于o2， 返回0 表示：o1和o2相等， 返回正数表示：o1大于o2。
             */
            public int compare(FlowAndRateData o1, FlowAndRateData o2) {

                // 按照流量进行降序排列
                if (o1.getFlowData() < o2.getFlowData()) {
                    return 1;
                }
                if (o1.getFlowData() == o2.getFlowData()) {
                    return 0;
                }
                return -1;
            }
        });

        return list;

    }

    /**
     * @param @param  type uv/session
     * @param @param  reg "(.*3PinDsyw,-1,-1.*3PinDsyw,-1,-1.*)"路径正则
     * @param @param  param 相关的平台，时间的查询条件
     * @param @return 设定文件
     * @return int 返回类型
     * @throws
     * @Title: getPathNum
     * @Description: 自定义漏斗获取uv/session 数据量
     */
    private Long getPathNum(String type, String reg, FlowFunnelData param) throws Exception{
        String operPath = "";
        /* uv/session 查询不通的表 */
        if (type.equals("uv")) {
            operPath = "dtOperPath";
        } else {
            operPath = "sessionOperPath";
        }
        reg = "(.*" + reg + ".*)";
        log.info("-------------reg-----------" + reg);
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.boolQuery()
                                .must(QueryBuilders.termsQuery("platformCode", param.getPlatformCodeList()))
                                .must(QueryBuilders.rangeQuery("operateDate").from(param.getBeginDate()).to(param.getEndDate())
                                 .includeLower(true).includeUpper(true)).must(QueryBuilders.regexpQuery("operatePath",reg)))
                                 .withIndices("flow_v1").withPageable(new PageRequest(0, 10000000)).withTypes(operPath).build();

        long amount = template.elasticsearchTemplate().count(searchQuery,FlowFunnelData.class);
        return amount;
    }
}
